﻿using WorkflowCore.Interface;
using WorkflowCore.Models;

namespace Service.CertWorkFlow.Steps
{
    public class ValidateDnsTxtRecord : StepBodyAsync
    {
        public override async Task<ExecutionResult> RunAsync(IStepExecutionContext context)
        {
            var data = context.Workflow.Data as WorkflowData;
            int retryTimes = 10;
            var successed = false;
            var message = "";
            while (retryTimes > 0&& successed==false)
            {
                var res = await data.CertService.ValidateDnsTxtRecord(data.Dns01ChallengeValidationDetails);
                if (res.Result)
                {
                    successed = true;
                    message = "DNS记录认证成功";
                }
                else
                {
                    retryTimes--;
                    var sleepTime = (10 - retryTimes) * 1000;
                    Thread.Sleep(sleepTime);
                    message = $"DNS记录认证失败,重试 {10 - retryTimes} , {(sleepTime/1000)} 秒后重新尝试";
                }
                data.Action?.Invoke(message);
            }
            if (!successed)
            {
                data.Action.Invoke("DNS记录认证失败，强制执行证书下发");
            }
            return ExecutionResult.Next();
        }
    }
}
